var express = require('express');
var async = require('async');

var utils = require('../functions/utils');
var router = express.Router();

router.post('/', function(req,res)
{
/*
	Input parameters 
	 *		register  '0':login , '1':register	
	 *		loginId
	 *  	loginPwd
*/
	var register = req.body.register;	utils.checkParamValue('register' , register);
	var loginId = req.body.loginId;		utils.checkParamValue('loginId' , loginId);
	var loginPwd = req.body.loginPwd;	utils.checkParamValue('loginPwd' , loginPwd);

	// lower case 
	loginId = loginId.toLowerCase();

	// session id 없으니 loginId로 대신한다. 
	req.body.sessionId = loginId;
	utils.callLog(req);

	// 금지어 체크
	utils.checkProhibitedWord(loginId);

	if(global.config.debug)
	{
		if(register == '0')
		    utils.debug(req.originalUrl + ' : login');
		else
			utils.debug(req.originalUrl + ' : register');
	}

	// email check
	if(!utils.emailCheck(loginId))
	{
		var err = new Error('Invalid email address : ' + loginId);
		err.code = '524';
		throw err;
	}

	var _list = loginId.split("@");

	var userName = _list[0];
	var domain = _list[1];

	var userKey = null;
	var result = null;

	// 패스워드 암호화한다. 
	loginPwd = utils.passwordEncrypt(loginPwd);

//////////////////////////////////////////////////////////////////////////////////


		// mail domain check 후 sp call 
		async.waterfall([
			function(cb)
			{
				//  check and register : replica 에서 체크하면 replication lag 때문에 중복될 가능성때문에 몽땅 master 에서 처리한다.
				global.master_db.connection.getConnection(function(err,connection)
				{
					if(err)
					{
						throw err;
					}

					var input_param = [register, loginId , loginPwd ,userName];

					var sql = 'call api_checkAndLoginWithEmail_1_0(? , ? , ?  , ? ,@key, @result); SELECT @key as userKey , @result AS result';
					var query = connection.query(sql, input_param , function (err, rows) 
					{
						connection.release();
						if(err)
						{
							throw err;	
						}


						result = rows[1][0].result;
						userKey = rows[1][0].userKey;

						// next 
						cb();

					}); // call api_checkAccount_1_0

				}); // getConnection

			},
			function(cb)
			{
				var ret = { 'body' : {} };	 

				switch(result)
				{
					case 200:
						ret.code=result;
						ret.body.userKey=userKey;
						break;
					case 520:
						var err = new Error('Register Account : Email is in use [' + loginId +']');
						err.code = '520';
						throw err;
						break;
					case 522:
						var err = new Error('Login Account : Unregistered email [' + loginId + ']');
						err.code = '522';
						throw err;
						break;

					case 524:
						var err = new Error('Login Account : Email and Pwd mismatch [' + loginId + '],[' + loginPwd+']');
						err.code = '524';
						throw err;
						break;
					default:
						throw new Error();

				}

				res.json(ret);
				res.end();

			}


		]); // waterfall

//////////////////////////////////////////////////////////////////////////////////


	
});

module.exports = router;